const express = require('express');
const router = express.Router();
const { Category, Course } = require('../../models');
const { Op } = require('sequelize');
const { success, failure } = require('../../utils/responses');
const { Conflict, NotFound } = require('http-errors');
/**
 * 白名单参数过滤
 * */
const filterBody = (data) => {
  return {
    name: data.name,
    rank: data.rank,
  };
};

const conditionParam = {
  include: [
    {
      model: Course,
      as: 'courses',
      attributes: ['id', 'name'],
    },
  ],
};

/**
 * 公共方法: 查询当前分类
 * */
async function getCategory(req) {
  const { id } = req.params;
  const category = await Category.findByPk(id, conditionParam);
  if (!category) {
    throw new NotFound(`ID: ${id}的分类为找到`);
  }
  return category;
}

/**
 * 查询分类列表
 * */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    // 当前第几页，如果不传默认第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 当前多少条数据，如果不传默认10条数据
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算offset
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      where: {},
      order: [
        ['ranK', 'ASC'],
        ['id', 'DESC'],
      ],
      limit: pageSize,
      offset,
    };
    const name = decodeURIComponent(query.name);
    if (name) {
      condition.where.name = {
        [Op.like]: `%${name}%`,
      };
    }
    console.log(condition, 'condition');
    // const categories = await Category.findAll(condition);
    const { count: total, rows } = await Category.findAndCountAll(condition);
    success(res, '查询成功', {
      categories: rows,
      pagination: {
        total,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询分类详情
 * */
router.get('/:id', async function (req, res) {
  try {
    const categories = await getCategory(req);
    success(res, '查询成功', { categories });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建分类
 * */
router.post('/', async function (req, res) {
  try {
    const body = filterBody(req.body);
    const categories = await Category.create(body);
    success(res, '创建成功', { categories }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除分类
 * */
router.delete('/:id', async function (req, res) {
  try {
    const category = await getCategory(req);
    const count = await Course.count({ where: { categoryId: req.params.id } });
    if (count > 0) {
      throw new Conflict('当前分类有课程，无法删除');
    }
    await category.destroy();
    success(res, '删除成功');
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新分类
 * */
router.put('/:id', async function (req, res) {
  try {
    const category = await getCategory(req);
    const body = filterBody(req.body);
    const data = await category.update(body);
    success(res, '更新成功', data);
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
